#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RAG系统问题诊断脚本
"""

import sys
import os
import json
import traceback

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def diagnose_rag_system():
    """诊断RAG系统问题"""
    print("=" * 60)
    print("RAG系统问题诊断")
    print("=" * 60)
    
    # 1. 检查Python环境
    print("1. Python环境检查:")
    print(f"   Python版本: {sys.version}")
    print(f"   当前工作目录: {os.getcwd()}")
    
    # 2. 检查文件存在性
    print("\n2. 文件检查:")
    files_to_check = [
        'ultra_simple_rag.py',
        'simple_rag_system.py', 
        'rag_system.py',
        'app_new.py',
        'knowledge_base'
    ]
    
    for file in files_to_check:
        if os.path.exists(file):
            print(f"   ✓ {file} - 存在")
        else:
            print(f"   ✗ {file} - 不存在")
    
    # 3. 测试超简化版RAG系统
    print("\n3. 测试超简化版RAG系统:")
    try:
        from ultra_simple_rag import UltraSimpleRAG
        print("   ✓ UltraSimpleRAG模块导入成功")
        
        # 测试初始化
        rag = UltraSimpleRAG()
        print("   ✓ UltraSimpleRAG初始化成功")
        
        # 测试基本功能
        stats = rag.get_knowledge_stats()
        print(f"   ✓ 知识库统计: {stats['total_knowledge']}条知识")
        
        # 测试问答
        result = rag.get_answer("乳腺癌有什么症状？")
        print(f"   ✓ 问答功能测试: 置信度 {result['confidence']:.2f}")
        print(f"   ✓ 答案预览: {result['answer'][:100]}...")
        
    except Exception as e:
        print(f"   ✗ UltraSimpleRAG测试失败: {e}")
        traceback.print_exc()
    
    # 4. 测试简化版RAG系统
    print("\n4. 测试简化版RAG系统:")
    try:
        from simple_rag_system import SimpleRAGSystem
        print("   ✓ SimpleRAGSystem模块导入成功")
        
        # 测试初始化
        rag = SimpleRAGSystem()
        print("   ✓ SimpleRAGSystem初始化成功")
        
        # 测试基本功能
        stats = rag.get_knowledge_stats()
        print(f"   ✓ 知识库统计: {stats['total_knowledge']}条知识")
        
        # 测试问答
        result = rag.get_answer("乳腺癌有什么症状？")
        print(f"   ✓ 问答功能测试: 置信度 {result['confidence']:.2f}")
        
    except Exception as e:
        print(f"   ✗ SimpleRAGSystem测试失败: {e}")
        traceback.print_exc()
    
    # 5. 测试完整版RAG系统
    print("\n5. 测试完整版RAG系统:")
    try:
        from rag_system import RAGSystem
        print("   ✓ RAGSystem模块导入成功")
        
        # 测试初始化
        rag = RAGSystem()
        print("   ✓ RAGSystem初始化成功")
        
        # 测试基本功能
        stats = rag.get_knowledge_stats()
        print(f"   ✓ 知识库统计: {stats['total_knowledge']}条知识")
        
        # 测试问答
        result = rag.get_answer("乳腺癌有什么症状？")
        print(f"   ✓ 问答功能测试: 置信度 {result['confidence']:.2f}")
        
    except Exception as e:
        print(f"   ✗ RAGSystem测试失败: {e}")
        traceback.print_exc()
    
    # 6. 检查Flask应用
    print("\n6. 检查Flask应用:")
    try:
        from app_new import app, RAG_AVAILABLE, rag_system
        print(f"   ✓ Flask应用导入成功")
        print(f"   ✓ RAG_AVAILABLE: {RAG_AVAILABLE}")
        print(f"   ✓ rag_system: {'已初始化' if rag_system else '未初始化'}")
        
        # 测试RAG系统初始化
        if RAG_AVAILABLE and rag_system is None:
            print("   ⚠ RAG系统可用但未初始化，尝试初始化...")
            try:
                from ultra_simple_rag import UltraSimpleRAG
                rag_system = UltraSimpleRAG()
                print("   ✓ RAG系统初始化成功")
            except Exception as e:
                print(f"   ✗ RAG系统初始化失败: {e}")
        
    except Exception as e:
        print(f"   ✗ Flask应用检查失败: {e}")
        traceback.print_exc()
    
    # 7. 检查知识库文件
    print("\n7. 检查知识库文件:")
    kb_file = os.path.join('knowledge_base', 'knowledge_base.json')
    if os.path.exists(kb_file):
        try:
            with open(kb_file, 'r', encoding='utf-8') as f:
                kb_data = json.load(f)
            print(f"   ✓ 知识库文件存在，包含 {len(kb_data)} 条知识")
        except Exception as e:
            print(f"   ✗ 知识库文件读取失败: {e}")
    else:
        print("   ✗ 知识库文件不存在")
    
    # 8. 检查依赖库
    print("\n8. 检查依赖库:")
    dependencies = [
        'flask',
        'numpy',
        'json',
        'os',
        'sys',
        'logging'
    ]
    
    for dep in dependencies:
        try:
            __import__(dep)
            print(f"   ✓ {dep} - 已安装")
        except ImportError:
            print(f"   ✗ {dep} - 未安装")
    
    print("\n" + "=" * 60)
    print("诊断完成")
    print("=" * 60)

def test_rag_manually():
    """手动测试RAG功能"""
    print("\n" + "=" * 60)
    print("手动测试RAG功能")
    print("=" * 60)
    
    try:
        from ultra_simple_rag import UltraSimpleRAG
        rag = UltraSimpleRAG()
        
        # 测试问题列表
        test_questions = [
            "乳腺癌有什么症状？",
            "如何诊断乳腺癌？",
            "乳腺癌怎么治疗？",
            "乳腺癌如何预防？",
            "乳腺癌分期是什么意思？"
        ]
        
        for i, question in enumerate(test_questions, 1):
            print(f"\n{i}. 问题: {question}")
            result = rag.get_answer(question)
            print(f"   答案: {result['answer'][:200]}...")
            print(f"   置信度: {result['confidence']:.2f}")
            print(f"   来源数量: {len(result['sources'])}")
            
    except Exception as e:
        print(f"手动测试失败: {e}")
        traceback.print_exc()

if __name__ == "__main__":
    diagnose_rag_system()
    test_rag_manually()
    input("\n按回车键退出...")
